import os
import sys
from pathlib import Path

# 添加项目根目录到Python路径
backend_dir = str(Path(__file__).parent.parent.parent.absolute())
if backend_dir not in sys.path:
    sys.path.insert(0, backend_dir)

from app.db.session import engine, SessionLocal
from app.core.config import settings
from app.db.init_knowledge_base import init_knowledge_base
from app.db.init_admin import init_admin
import logging
from app.models.base import Base
# 导入所有模型以确保它们被注册到Base.metadata
from app.models.learning import KnowledgeBase, Exercise, LearningPlan, LearningTask, Progress
from app.models.user import User

logger = logging.getLogger(__name__)

def init_db():
    """初始化数据库，创建所有表"""
    Base.metadata.create_all(bind=engine)
    logger.info("Database tables created successfully!")

def init():
    try:
        init_db()
        # 初始化数据库会话
        db = SessionLocal()
        try:
            init_knowledge_base()
            logger.info("Database initialized successfully with knowledge base")
        finally:
            db.close()
    except Exception as e:
        logger.error(f"Error initializing database: {e}")
        raise